package com.gnerv.pabu.plugin.utils;

import com.gnerv.pabu.plugin.config.MybatisPlusSettings;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.vfs.VirtualFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
public class ClassFileUtils {

    private static MybatisPlusSettings mybatisPlusSettings;

    static {
        mybatisPlusSettings = ServiceManager.getService(MybatisPlusSettings.class);
    }

    private ClassFileUtils() {
    }

    public static boolean writeStringToFile(String path, String name, Integer templatesIndex, Map map) {
        String javaCode = VelocityUtils.generate(mybatisPlusSettings.getTemplateGroup().getTemplates().get(templatesIndex).getCode(), map);
        File file = new File(path, name);
        try {
            FileUtils.writeStringToFile(file, javaCode, StandardCharsets.UTF_8.name());
        } catch (IOException e) {
            log.info("文件写入错误", e);
        }
        return true;
    }

    public static boolean writeStringToFile(String path, String name, String javaCode) {
        File file = new File(path, name);
        try {
            FileUtils.writeStringToFile(file, javaCode, StandardCharsets.UTF_8.name());
        } catch (IOException e) {
            log.info("文件写入错误", e);
        }
        return true;
    }

    public static boolean writeStringToFile(VirtualFile virtualFile, String name, String javaCode) {
        return writeStringToFile(virtualFile.getCanonicalPath(), name, javaCode);
    }

}
